<template>
  <div class="app-container">
    <el-form
      ref="passwordForm"
      :model="passwordForm"
      :rules="rules"
      label-width="80px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item
            label="旧密码"
            prop="old_password">
            <el-input
              type="password"
              v-model="passwordForm.old_password"
              placeholder="请输入旧密码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="新密码"
            prop="new_password">
            <el-input
              type="password"
              v-model="passwordForm.new_password"
              placeholder="请输入新密码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="确认密码"
            prop="re_new_password">
            <el-input
              type="password"
              v-model="passwordForm.re_new_password"
              placeholder="请输入新密码"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import CryptoJS from 'crypto-js';
import { userUpdatePassword } from '@/api/user';
export default {
  name:"changePassword",
  data(){
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.passwordForm.re_new_password !== '') {
          this.$refs.passwordForm.validateField('re_new_password');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.passwordForm.new_password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      passwordForm:{
        old_password:"",
        new_password:"",
        re_new_password:""
      },
      rules:{
        old_password:[
          { required: true, trigger: 'blur', message: '密码不能为空' }
        ],
        new_password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        re_new_password: [
          { validator: validatePass2, trigger: 'blur' }
        ],
      }
    }
  },
  methods:{
    handleSubmit(){
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          let params = {
            old_password: this.passwordForm.old_password,
            new_password: this.passwordForm.new_password
          }
          this.$emit('update:loadingButton', ['submit']);
          userUpdatePassword(params).then(res=>{
            this.$message.success(res.message)
            this.$emit('update:loadingButton', []);
            this.$emit('update:visible', false);
          }).catch(()=>{
            this.$emit('update:loadingButton', []);
          })
        }
      })
    }
  }
}
</script>